<template>
  <div class="container">
    <el-row :gutter="20">
      <!-- 搜索 -->
      <el-col :sm="12" :xs="24">
        <el-autocomplete
          class="inline-input"
          v-model="queryInfo.query"
          :fetch-suggestions="querySearch"
          placeholder="请输入内容"
          :trigger-on-focus="false"
          clearable
          @clear="onClearProc"
          @select="handleSelect"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="onSearch"
          ></el-button
        ></el-autocomplete>
      </el-col>
      <!-- 添加 -->
      <el-col class="opr-buttons" :sm="12" :xs="24">
        <el-button @click="addItem">
          <i class="el-icon-plus"></i>
          添 加</el-button
        >

        <el-button @click="uploadFile">
          <i class="el-icon-upload2"></i>
          批量导入</el-button
        >

        <el-button @click="openMiniProgram">
          <i class="el-icon-full-screen"></i>
          签约小程序</el-button
        >
      </el-col>
    </el-row>
    <!--#region 表格数据 -->
    <el-table
      id="data"
      :data="dataList"
      border
      stripe
      size="small"
      fit
      :default-sort="{ prop: 'createTime', order: 'descending' }"
    >
      <!-- 索引列 -->
      <!-- <el-table-column type="index" align="center">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column> -->

      <!-- <el-table-column prop="Indate" label="创建时间" align="center" sortable>
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          {{ new Date(scope.row.Indate).toLocaleDateString() }}
        </template>
      </el-table-column> -->

      <el-table-column
        v-for="item in columns"
        :key="item.key"
        :prop="item.key"
        :label="item.value"
        sortable
        align="center"
      >
      </el-table-column>

      <el-table-column
        width="120"
        prop="curStatus"
        label="状态"
        align="center"
        sortable
      >
        <template slot-scope="scope">
          <div v-if="scope.row.zt">
            <i class="el-icon-circle-check"></i>
            <span>已签约</span>
          </div>
          <div v-else>
            <i class="el-icon-circle-close"></i>

            <span>未签约</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300" align="center">
        <template slot-scope="scope">
          <el-row class="center">
            <el-col :span="8" class="center">
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-edit"
                @click="editItem(scope.row)"
                >修改</el-button
              >
            </el-col>
            <el-col :span="8" class="center">
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-delete"
                @click="deleteItem(scope.row)"
                >删除</el-button
              >
            </el-col>
            <el-col :span="8" class="center">
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-document"
                @click="showLog(scope.row)"
                >日志</el-button
              >
            </el-col>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <!-- #endregion -->

    <!-- #region 分页-->
    <div class="page-footer">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageIndex"
        :page-sizes="[1, queryInfo.pageSize, 10, 15, 100, total]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>

      <el-button class="exportFile" size="mini" @click="exportFile">
        <i class="el-icon-download"></i>
        导出</el-button
      >
    </div>

    <!-- #endregion -->
    <!-- #region 添加 -->
    <el-dialog
      :title="$language.local('添加')"
      :visible.sync="addDialogVisible"
      width="38%"
    >
      <el-form
        ref="addFromRef"
        :model="addForm"
        :rules="$rules"
        label-width="100px"
        status-icon
      >
        <template v-for="(value, key) in addForm">
          <template v-if="key === 'Sex'">
            <el-form-item :key="key" :label="$language.local(key)">
              <el-radio-group v-model="addForm[key]" class="sex">
                <el-radio label="1" border
                  ><i class="el-icon-male"></i> 男</el-radio
                >
                <el-radio label="2" border>
                  <i class="el-icon-female"></i>
                  女</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </template>

          <el-form-item
            v-else
            :key="key"
            :label="$language.local(key)"
            :prop="key"
          >
            <template v-if="key === 'BankName'">
              <el-select v-model="addForm[key]" filterable placeholder="请选择">
                <el-option
                  v-for="item in banks"
                  :key="item.BANKID"
                  :label="item.BANKNAME"
                  :value="item.BANKNAME"
                >
                </el-option>
              </el-select>
            </template>
            <template v-else-if="key === 'ServiceID'">
              <el-select v-model="addForm[key]" filterable placeholder="请选择">
                <el-option
                  v-for="item in serviceProvider"
                  :key="item.Id"
                  :label="item.ServiceName"
                  :value="item.Id"
                >
                </el-option>
              </el-select>
            </template>
            <template v-else-if="key === 'Merchant'">
              <el-select v-model="addForm[key]" filterable placeholder="请选择">
                <el-option
                  v-for="item in merchants"
                  :key="item.Id"
                  :label="item.customerName"
                  :value="item.Id"
                >
                </el-option>
              </el-select>
            </template>
            <template v-else-if="key === 'ServiceContentId'">
              <el-select v-model="addForm[key]" filterable placeholder="请选择">
                <el-option
                  v-for="item in serviceContent"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </template>
            <xy-input v-else v-model="addForm[key]" clearable></xy-input>
          </el-form-item>
        </template>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onAddSubmit('addFromRef')"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- #endregion -->

    <el-dialog title="修改" :visible.sync="editDialogVisible" width="30%">
      <el-form
        ref="editFromRef"
        :model="editFrom"
        :rules="$rules"
        label-width="80px"
        status-icon
      >
        <el-form-item
          v-for="(item, key) in editFormItemName"
          :key="key"
          :label="$language.local(key)"
          :prop="key"
        >
          <xy-input
            :disabled="key === 'EmpName' || key === 'EmpNo'"
            v-model="editFrom[key]"
            clearable
          ></xy-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onEditSubmit('editFromRef')"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <el-dialog title="批量导入" :visible.sync="uploadDialogVisible" width="30%">
      <el-upload
        class="upload-demo"
        drag
        :action="$http.baseUrl + '/api/employee/batchInput'"
        multiple
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">上传文件不超过500kb</div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="uploadDialogVisible = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <el-dialog title="认证小程序" :visible.sync="miniDialogVisible" width="30%">
      <img
        style="width: 100%"
        src="../../assets/static/img/miniProgram.jpg"
        alt=""
        srcset=""
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="miniDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      total: 0,
      columns: [
        {
          key: "EmpName",
          value: "姓名",
          width: 80,
        },
        {
          key: "IdCardNo",
          value: "身份证号",
          width: 80,
        },
        {
          key: "BankCardNo",
          value: "银行卡号",
          width: 80,
        },
        {
          key: "MerchantName",
          value: "合作企业",
          width: 180,
        },
        {
          key: "EmpPhone",
          value: "联系方式",
          width: 120,
        },
      ],
      dataList: [],
      searchInput: "",
      queryInfo: {
        query: "",
        pageSize: 10,
        pageIndex: 1,
      },
      user: null,
      addDialogVisible: false,
      editDialogVisible: false,
      miniDialogVisible: false,
      uploadDialogVisible: false,
      miniProgramUrl: "../../assets/static/img/miniProgram.jpg",
      addForm: {
        EmpName: "",
        IdCardNo: "",
        Sex: "",
        Merchant: "",
        BankName: "",
        BankCardNo: "",
        EmpPhone: "",
        ServiceID: "",
        ServiceContentId: "",
      },
      RmEmps: [],
      BankInfs: [],
      addFormItemName: {
        EmpName: "姓名",
        bankName: "开户行",
        bankCardNo: "银行卡号",
        empPhone: "手机号码",

        // taxCollectionRmEmps: "合作企业",
      },
      addFormRoles: [],
      editFrom: {},
      editFormItemName: {
        EmpNo: "",
        EmpName: "",
        MerchantName: "",
        BankName: "",
        BankCardNo: "",
        EmpPhone: "",
      },
      serviceProvider: [],
      serviceContent: [],
      merchants: [],
      banks: [],
    };
  },
  created() {
    this.user = this.$store.getters.user;

    this.getEmployee();
  },
  methods: {
    async getServiceProviderList() {
      let response = await this.$http.get(
        "/api/Common/GetServiceProviderList",
        {
          userId: this.user.userId,
        }
      );
      // console.log(response);
      this.serviceProvider = response.data.Data;
    },
    async getServiceContent() {
      let response = await this.$http.get("/api/Common/GetdictionaryItem", {
        userId: this.user.userId,
        typenum: "002",
      });
      // console.log(response);
      this.serviceContent = response.data.Data;
    },
    async getMerchants() {
      let response = await this.$http.get("/api/Merchant/GetList", {
        userId: this.user.userId,
        typenum: "002",
        pageSize: 100,
      });
      // console.log(response);
      this.merchants = response.data.Data;
    },
    async getBank() {
      let response = await this.$http.get("/api/Common/GetBankItem", {
        userId: this.user.userId,
      });
      console.log(response);
      this.banks = response.data.Data;
    },
    async getEmployee() {
      let requestBody = {
        userId: this.user.userId,
        pageSize: this.queryInfo.pageSize,
        page: this.queryInfo.pageIndex,
        keywords: this.queryInfo.query,
      };
      let res = await this.$http.get("/api/employee/GetList", requestBody);
      console.log(res);
      this.dataList = res.data.Data;
      this.total = res.data.TotalCount;
    },

    onSearch() {
      this.getEmployee();
    },
    async addItem() {
      this.addDialogVisible = true;
      this.getServiceProviderList();
      this.getServiceContent();
      this.getMerchants();
      this.getBank();
      // console.log(this.dataList[0]);
      // let response = await this.$http.Get("/api/BankInfs");
      // if (response.ok) {
      //   this.BankInfs = response.data;
      //   console.log(response);
      // }
    },
    editItem(item) {
      this.editDialogVisible = true;
      this.editFrom = item;
    },
    onEditSubmit(formName) {
      this.$refs[formName].validate(async (valided) => {
        if (!valided) {
          return;
        }

        try {
          console.log(this.editFrom);
          // let body = {
          //   userId: this.user.userId,
          //   id: this.editFrom.Id,
          //   mid: this.editFrom.MID,
          //   model: this.editFrom,
          // };
          let response = await this.$http.post(
            `/api/employee/Edit/${this.editFrom.Id}?userId=${this.user.userId}&mid=${this.editFrom.MID}`,
            this.editFrom
          );
          console.log(response);
          if (response.ok) {
            this.$message.success("修改成功");
            this.dataList = [this.editFrom];
            this.editDialogVisible = false;
          }
        } catch (error) {
          console.error(error);
          this.$message.error("修改失败");
        }
      });
    },
    async deleteItem(item) {
      console.log(item);
      let result = await this.$confirm(`确认删除 ${item.EmpName}？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch((err) => err);
      if (result === "confirm") {
        let response = await this.$http.delete(
          `/api/employee/Delete/${item.Id}?userId=${this.user.userId}&mid=${item.MID}`
        );
        console.log(response);
        if (response.data.Code == 200) {
          this.getEmployee();
        }
        this.$message.success("删除成功");
      }
    },
    async querySearch(queryString, cb) {
      let results;
      if (queryString) {
        let requestBody = {
          userId: this.user.userId,
          pageSize: this.queryInfo.pageSize,
          page: this.queryInfo.pageIndex,
          keywords: this.queryInfo.query,
        };
        let response = await this.$http.get(
          "/api/employee/GetList",
          requestBody
        );
        // console.log(response);
        results = response.data.Data;
      }

      results.forEach((v) => {
        v.value = v.EmpName;
      });
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.empName
            .toLowerCase()
            .indexOf(queryString.toLowerCase()) === 0
        );
      };
    },
    onClearProc() {},
    handleSelect(item) {
      this.dataList = [item];
    },
    itemStateChange() {},
    handleSizeChange(newPageSize) {
      this.queryInfo.pageSize = newPageSize;
      this.getEmployee(this.queryInfo);
    },
    handleCurrentChange(newPageIndx) {
      this.queryInfo.pageIndex = newPageIndx;
      this.getEmployee(this.queryInfo);
    },
    exportFile() {},

    onAddSubmit(formName) {
      this.$refs[formName].validate(async (valided) => {
        if (!valided) {
          return;
        }
        try {
          // this.addForm.employee.empName = this.addForm.empName;
          console.log(this.addForm);
          let response = await this.$http.post(
            `/api/employee/Create?userId=${this.user.userId}&MID=${this.addForm.Merchant}&ServiceContentId=${this.addForm.ServiceContentId}`,
            this.addForm
          );
          console.log(response);
          if (response.data.Code == 200) {
            console.log(response);
            this.$message.success("添加成功");
            this.dataList = [response.data.Data];
            this.addDialogVisible = false;
          } else {
            throw response;
          }
        } catch (error) {
          console.error(error);
          if (error.data) {
            this.$message.error(error.data.Message);
          } else {
            this.$message.error("添加失败");
          }
        }
      });
    },
    openMiniProgram() {
      this.miniDialogVisible = true;
    },
    uploadFile() {
      this.uploadDialogVisible = true;
    },
    showLog() {},
  },
};
</script>

<style lang="less" scoped>
@media screen and (max-width: 768px) {
  .el-row {
    .el-col {
      margin-bottom: 1rem;
      &.opr-buttons {
        display: flex;
        flex-direction: column;

        .el-button {
          margin: 0 0 1rem 0;
        }
      }
    }
  }
}
.el-form {
  padding: 0 3rem;
}
.el-select {
  width: 100%;
}
.sex {
  widows: 100%;
  display: flex;
  justify-content: space-between;
}
.container {
  background-color: #fff;

  .el-autocomplete {
    width: 100%;
  }
  .el-table {
    height: 520px;
    overflow: scroll;
    margin-top: 15px;

    .el-tooltip {
      margin-left: 0;
    }
  }
  .el-pagination {
    margin-top: 15px;
  }
  .page-footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .exportFile {
      margin-top: 15px;
    }
  }
}
i {
  margin-right: 5px;
}
.el-icon-circle-check {
  color: green;
}
.el-icon-circle-close {
  color: red;
}
</style>
